<?php

/**
 * This is the model class for table "history".
 *
 * The followings are the available columns in table 'history':
 * @property string $uuid
 * @property string $user
 * @property string $ip
 * @property string $header
 * @property string $footer
 * @property string $body
 */
class History extends CActiveRecord
{
	private $style_counter = 0;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return History the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'history';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('uuid, user, ip, header, footer, body, comment, timestamp, shared, loadCount', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('uuid, user, ip, header, footer, body, timestamp, shared, loadCount', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'uuid'      => Yii::t('model', 'Uuid'),
			'user'      => Yii::t('model', 'User'),
			'ip'        => Yii::t('model', 'Ip'),
			'header'    => Yii::t('model', 'Header'),
			'footer'    => Yii::t('model', 'Footer'),
			'comment'   => Yii::t('model', 'Comment'),
			'body'      => Yii::t('model', 'Body'),
			'timestamp' => Yii::t('model', 'Timestamp'),
			'shared'    => Yii::t('model', 'Shared'),
			'loadCount' => Yii::t('model', 'Load count'),
		);
	}
	
	/**
	 * The method returns the correct time stamp
	 * 
	 * @return String
	 */
	public function getTimestamp(){
		$result = '';
		
		if ($this->timestamp + 120 >= time()) {
			$result = 'Moments ago';
		} else if ($this->timestamp + 120 <= time() && $this->timestamp + 60*59 >= time()) {
			$result = round((time()-$this->timestamp)/60, 0) . ' minutes ago';
		} else {
			$result = Yii::app()->DateFormatter->formatDateTime($this->timestamp, "long", "short");
		}
		
		return $result;
	}
	
	/**
	 * The method returns the download link for the history entrie if a file exists.
	 * 
	 * @return String
	 */
	public function getDownloadLink(){
		$result = null;
		$model = new InputForm();
		
		$file_formats = $model->getFormatOptions();
		$file_formats[] = '';
		
		foreach ($file_formats AS $option) {
			if (file_exists('download/utd_export_' . $this->uuid . '.' . $option)) {
				$result = 'download/utd_export_' . $this->uuid . '.' . $option;
				break;
			}
		}
		
		return $result;
	}
	
	/**
	 * Returns a unique list of tags used in the body
	 * 
	 * @return array
	 */
	public function getUniqueTags(){
		$result = array();
		preg_match_all("#\s*{(.*?)}#si", $this->body, $matches);
		
		foreach ($matches[1] AS $match) {
			$tmp = explode(':', $match);
			$result[] = $tmp[0];
		}
		
		return array_unique($result);
	}
	
	/**
	 * Returns the unique list of tags in a well formated form
	 * 
	 * @return String
	 */
	public function getUniqueTagsList(){
		$result = '';
		
		foreach ($this->getUniqueTags() AS $tag) {
			$result .= '<span class="label' . $this->getTagStyle() . '" style="font-size:9px">' . $tag . '</span> ';
	    }
	    
	    return $result;
	}
	
	/**
	 * Returns a random style for the list labels
	 * 
	 * @return String
	 */
	public function getTagStyle(){
		$styles = array('', ' label-success', ' label-warning', ' label-important', ' label-info', ' label-inverse');
		
		if ($this->style_counter >= sizeof($styles)-1) {
			$this->style_counter = 0;
		} else {
			$this->style_counter++;
		}
		
		return $styles[$this->style_counter];
	}
	
	/**
	 * Get last saved entry
	 * 
	 * @return boolean
	 */
	public static function isLastSubmittedTemplateAvailable(){
		$criteria = new CDbCriteria;
		
		if (Yii::app()->user->getId()) {
			$criteria->addCondition('user = "' . Yii::app()->user->getId() . '"', 'OR');
		} 
		
		$criteria->addCondition('shared = "1"', 'OR');
		$criteria->limit = 1;
		$criteria->order = 'timestamp DESC';
		
		return History::model()->count($criteria) > 0;
	}
	
	/**
	 * Get last saved entry
	 * 
	 * @return String
	 */
	public static function getLastSubmittedTemplateId(){
		$criteria = new CDbCriteria;
		
		if (Yii::app()->user->getId()) {
			$criteria->addCondition('user = "' . Yii::app()->user->getId() . '"', 'OR');
		} 
		
		$criteria->addCondition('shared = "1"', 'OR');
		$criteria->limit = 1;
		$criteria->order = 'timestamp DESC';
		
		return History::model()->find($criteria)->uuid;
	}
}